#include "mainwindow.h"
#include <QCoreApplication>
#include <QFile>
#include <QKeyEvent>
#include <QMessageBox>
#include <QRandomGenerator>
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_ptrStumysql(nullptr)
{
    ui->setupUi(this);

    QFile fread;
    //auto str=QCoreApplication::applicationDirPath();
    fread.setFileName(":/dlg.css");
    fread.open(QIODevice::ReadOnly);
    QString strQss = fread.readAll();
    m_dlgLogin.setStyleSheet(strQss); //css样式在登录界面实现
    fread.close();

    fread.setFileName(":/main.css");
    fread.open(QIODevice::ReadOnly);
    strQss = fread.readAll();
    this->setStyleSheet(strQss); //主界面样式实现

    m_dlgLogin.show();
    auto f = [&]() { this->show(); };
    connect(&m_dlgLogin, &Page_login::sendLoginSuccess, this, f);
    connect(&m_dlgLogin,
            &Page_login::sendLoginname,
            this,
            &MainWindow::onLoginSuccessful); //传用户名参数

    ui->treeWidget->clear();
    ui->treeWidget->setColumnCount(1); //设置树控件的列数为1
    QStringList l;
    l << "学生信息管理系统";
    QTreeWidgetItem *pf = new QTreeWidgetItem(ui->treeWidget, l);
    ui->treeWidget->addTopLevelItem(pf);
    l.clear();
    l << "学生管理";
    QTreeWidgetItem *p1 = new QTreeWidgetItem(pf, l);
    l.clear();
    l << "管理员管理";
    QTreeWidgetItem *p2 = new QTreeWidgetItem(pf, l);
    pf->addChild(p1);
    pf->addChild(p2);
    ui->treeWidget->expandAll(); //展开树控件的父节点
    // 创建新页面的实例
    connect(ui->treeWidget, &QTreeWidget::itemClicked, this, &MainWindow::onTreeItemClicked);
    m_ptrStumysql = stumySql::getinstance();
    m_ptrStumysql->init(); //数据库的连接
    updateTable();         //刷新
}
void MainWindow::onTreeItemClicked(QTreeWidgetItem *item, int column)
{
    if (item->text(column) == "管理员管理") {
        newPage = new AdminPage;
        // 添加新页面到QStackedWidget的索引为1的位置
        ui->stackedWidget->insertWidget(1, newPage);
        // 设置索引为1的页面为当前显示页面
        ui->stackedWidget->setCurrentIndex(1);
        ui->stackedWidget->setCurrentIndex(
            1); // 显示管理员管理界面，假设管理员管理界面在堆叠窗口中的索引为1
    } else if (item->text(column) == "学生管理") {
        ui->stackedWidget->setCurrentIndex(0);
    }
}
MainWindow::~MainWindow()
{
    delete ui;
}

// void MainWindow::keyPressEvent(QKeyEvent *event)//处理键盘按键按下事件,是在主界面按下时触发的事件
// {
//     if(event->key()==Qt::Key_F6)//按下对应的按键key_F6,指的就是键盘上的F6,就会在对应界面实现css的样式
//     {
//         QFile f;
//         auto str=QCoreApplication::applicationDirPath();
//         f.setFileName(str+"//"+"stuqss.css");
//         f.open(QIODevice::ReadOnly);
//         QString strQss =f.readAll();
//         this->setStyleSheet(strQss);
//         m_dlgLogin.setStyleSheet(strQss);//css样式在登录界面实现
//     }
// }

void MainWindow::on_btn_exit_clicked()
{
    exit(0);
}

void MainWindow::onLoginSuccessful(const QString &username)
{
    ui->le_user->setText(username);
}

void MainWindow::on_btn_simulation_clicked()
{
    //制作10条学生数据
    QRandomGenerator g, c;
    g.seed(0); //种子(seed)是用来初始化随机数生成器的一个初始值。种子决定了随机数生成器的起始状态
    c.seed(0);
    QFile f;
    int count = 0;
    //auto str=QCoreApplication::applicationDirPath();
    f.setFileName(":/randname.txt");
    if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        while (count <= 10 && !f.atEnd()) {
            QString line = f.readLine();
            line = line.simplified(); //出现了存入l_names的名字后面有空格的问题,simplified可以去掉字符串两头的空格
            if (!line.isEmpty()) {
                m_lNames.append(line);
                count++;
            }
        }
        f.close();
    } else {
        qDebug() << "Failed to open file";
    }
    for (int i = 0; i < m_lNames.size(); i++) {
        auto grade = g.bounded(7, 10); //bounded是随机范围
        auto uiclass = g.bounded(1, 8);
        stuInfo info;
        info.name = m_lNames[i];
        info.age = rand() % 70;
        info.grade = grade;
        info.uiclass = uiclass;
        info.studentid = i;
        info.phone = "13329924486";
        info.wechat = "13329924486";
        m_ptrStumysql->addstu(info);
    }
    updateTable();
}

void MainWindow::on_brn_add_clicked()
{
    m_dlgAddStu.setType(true);
    m_dlgAddStu.exec();
    updateTable();
}

void MainWindow::on_btn_clear_clicked()
{
    m_ptrStumysql->clearStuTable();

    updateTable();
}

void MainWindow::updateTable()
{
    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(9);
    QStringList l;
    l << "序号" << "id" << "姓名" << "年龄" << "年级" << "班级" << "学号" << "电话号码" << "微信";
    ui->tableWidget->setHorizontalHeaderLabels(l);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //每次选中会选中一行
    // ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);//决定可不可以选多行,但要按住ctrl
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    auto cnt = m_ptrStumysql->getStuCnt();
    ui->lb_cnt->setText(QString("学生总数：%1").arg(cnt));
    QList<stuInfo> lStudents = m_ptrStumysql->getPageStu(0, cnt);
    ui->tableWidget->setRowCount(cnt);
    for (int i = 0; i < lStudents.size(); i++) {
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(i)));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(lStudents[i].id)));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(lStudents[i].name));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(lStudents[i].age)));
        ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(lStudents[i].grade)));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(lStudents[i].uiclass)));
        ui->tableWidget->setItem(i,
                                 6,
                                 new QTableWidgetItem(QString::number(lStudents[i].studentid)));
        ui->tableWidget->setItem(i, 7, new QTableWidgetItem(lStudents[i].phone));
        ui->tableWidget->setItem(i, 8, new QTableWidgetItem(lStudents[i].wechat));
    }
}

void MainWindow::on_btn_del_clicked()
{
    int i = ui->tableWidget->currentRow();
    if (i >= 0) {
        int id = ui->tableWidget->item(i, 1)->text().toUInt();
        m_ptrStumysql->delStu(id);
        updateTable();
        QMessageBox::information(nullptr, "信息", "删除成功");
    }
}

void MainWindow::on_btn_update_clicked()
{
    stuInfo info;
    int i = ui->tableWidget->currentRow();
    if (i >= 0) {
        info.id = ui->tableWidget->item(i, 1)->text().toUInt();
        info.name = ui->tableWidget->item(i, 2)->text();
        info.age = ui->tableWidget->item(i, 3)->text().toUInt();
        info.grade = ui->tableWidget->item(i, 4)->text().toUInt();
        info.uiclass = ui->tableWidget->item(i, 5)->text().toUInt();
        info.studentid = ui->tableWidget->item(i, 6)->text().toUInt();
        info.phone = ui->tableWidget->item(i, 7)->text();
        info.wechat = ui->tableWidget->item(i, 8)->text();
        m_dlgAddStu.setType(false, info);
        m_dlgAddStu.exec();
    }
    updateTable();
}

void MainWindow::on_btn_search_clicked()
{
    QString strFilter = ui->le_search->text();
    if (strFilter.isEmpty()) {
        updateTable();
        return;
    }
    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(9);
    QStringList l;
    l << "序号" << "id" << "姓名" << "年龄" << "年级" << "班级" << "学号" << "电话号码" << "微信";
    ui->tableWidget->setHorizontalHeaderLabels(l);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //每次选中会选中一行
    // ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);//决定可不可以选多行,但要按住ctrl
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    auto cnt = m_ptrStumysql->getStuCnt();
    ui->lb_cnt->setText(QString("学生总数：%1").arg(cnt));
    QList<stuInfo> lStudents = m_ptrStumysql->getPageStu(0, cnt);
    //ui->tableWidget->setRowCount(cnt);

    int index = 0;
    for (int i = 0; i < lStudents.size(); i++) {
        if (!lStudents[i].name.contains(strFilter)) {
            continue;
        }
        ui->tableWidget->setItem(index, 0, new QTableWidgetItem(QString::number(index + 1)));
        ui->tableWidget->setItem(index, 1, new QTableWidgetItem(QString::number(lStudents[i].id)));
        ui->tableWidget->setItem(index, 2, new QTableWidgetItem(lStudents[i].name));
        ui->tableWidget->setItem(index, 3, new QTableWidgetItem(QString::number(lStudents[i].age)));
        ui->tableWidget->setItem(index,
                                 4,
                                 new QTableWidgetItem(QString::number(lStudents[i].grade)));
        ui->tableWidget->setItem(index,
                                 5,
                                 new QTableWidgetItem(QString::number(lStudents[i].uiclass)));
        ui->tableWidget->setItem(index,
                                 6,
                                 new QTableWidgetItem(QString::number(lStudents[i].studentid)));
        ui->tableWidget->setItem(index, 7, new QTableWidgetItem(lStudents[i].phone));
        ui->tableWidget->setItem(index, 8, new QTableWidgetItem(lStudents[i].wechat));
        index++;
    }
    ui->tableWidget->setRowCount(index);
}
